package com.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @className: UDPOutputStream
 * @description: UDP输出流
 * @author: Kuangkeli
 * @date: 2024/07/01 11:20
 **/
public class UDPOutputStream extends OutputStream {
    private DatagramSocket socket;
    private String address;
    private int port;

        public UDPOutputStream(DatagramSocket socket, String address, int port) {
        this.socket = socket;
        this.address = address;
        this.port = port;
    }

    /**
     * 写入单字节数据
     * @param b   the {@code byte}.
     * @throws IOException
     */
    @Override
    public void write(int b) throws IOException {
        byte[] buffer = new byte[1];
        buffer[0] = (byte) b;
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
                java.net.InetAddress.getByName(address), port);
        socket.send(packet);
    }

    /**
     * 写入字节数组
     * @param b     the data.
     * @param off   the start offset in the data.
     * @param len   the number of bytes to write.
     * @throws IOException
     */
    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        DatagramPacket packet = new DatagramPacket(b, off, len,
                java.net.InetAddress.getByName(address), port);
        socket.send(packet);
    }
}
